package stark.app.function.shortcut;

import android.content.pm.PackageInfo;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.ActivityShortcutDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.AppUtil;
import stark.common.basic.utils.RxUtil;

/**
 * Author：daizhongbin on 2021/8/20
 * Email：1027154338@qq.com
 * Desc:
 */
public class ShortcutDemoActivity extends BaseNoModelActivity<ActivityShortcutDemoBinding> {

    @Override
    protected int onCreate() {
        return R.layout.activity_shortcut_demo;
    }

    @Override
    protected void initView() {
        //layout manager
        GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
        mDataBinding.rvPackage.setLayoutManager(layoutManager);
        //adapter
        StPackageAdapter packageAdapter = new StPackageAdapter();
        packageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (!ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
                    ToastUtils.showShort("当前设备桌面应用不支持创建快捷方式");
                    return;
                }
                showCreateDialog(packageAdapter.getItem(position));
            }
        });
        mDataBinding.rvPackage.setAdapter(packageAdapter);

        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<PackageInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<PackageInfo>> emitter) {
                emitter.onNext(AppUtil.getPackagesWithLaunchIntent());
            }

            @Override
            public void accept(List<PackageInfo> packageInfos) {
                dismissDialog();
                packageAdapter.setNewInstance(packageInfos);
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideCreateDialog();
    }

    private ShortcutCreateDialog mDialog;

    private void showCreateDialog(PackageInfo packageInfo) {
        if (mDialog == null) {
            mDialog = new ShortcutCreateDialog(this);
        }
        mDialog.setPackageInfo(packageInfo);
        mDialog.show();
    }

    private void hideCreateDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

}
